<template>
    <van-loading v-if="loading" class="loading" />
    <template v-else>
        <header class="header">
            <div class="back" @click="goBack">
                <van-icon name="arrow-left" size="30" />
            </div>
            <div class="title">{{ comic.title }}</div>
        </header>
        <div class="recommend">
            <van-image class="logo" :src="Logo" fit="contain"></van-image>
            <div class="slogan">
                <p>更多精彩内容</p>
                <p>尽在哔哩哔哩漫画</p>
            </div>
            <div class="openApp">
                <van-button color="#fb7299" round class="button">打开App</van-button>
            </div>
        </div>
        <div class="banner">
            <van-image :src="proxyImageUrl(comic.horizontal_cover)" class="cover"></van-image>
            <div class="info">
                <div class="title">{{ comic.title }}</div>
                <div class="other">{{ getAuthors(comic.author_name) }} 。{{ comic.styles[0] }}.{{ comic.id }}</div>
            </div>
        </div>
        <div class="subscribe">
            <div class="collection">
                <van-icon name="star-o" size="40" /> <span>追漫</span>
            </div>
            <van-button round class="button" color="#fb7299">免费看{{ getLastFreeEp(comic.ep_list)
                }}话</van-button>
        </div>
        <div class="tags">
            <ul>
                <li v-for="tag in getTags(comic.tags)">
                    {{ tag }}
                </li>
            </ul>
        </div>
        <!-- 简介 -->
        <div class="classic_lines">
            <p :class="{ expanded: !toggleStatus }"> {{ comic.classic_lines }} </p>
            <div class="toggle" @click="toggleStatus = !toggleStatus"> <van-icon :name="toggleIcon" size="14" /> </div>
        </div>
        <!-- 章节目录 -->
        <div class="chapter-menu">
            <div class="title">
                <span>全部章节({{ comic.total }})</span>
                <!-- 排序开关 -->
                <div class="sorting" @click="selectSort">
                    <span>{{ sortingOrder }}</span>
                    <van-icon :name="sortingOrderIcon" size="18" />
                </div>
            </div>
            <!--  章节菜单 -->
            <div class="menu-box">
                <div class="menu-btn" v-for="(menu, index) in menus" :key="index"
                    @click="goToShow(menu, menu.is_locked)">
                    <span> {{ menu.short_title }}</span>
                    <van-icon name="vip-card" class="lock" size="24" v-if="menu.is_locked" /> <!-- VIP 图标 -->
                </div>
            </div>
        </div>
        <div class="comments">
            <div class="title">漫画点评</div>
            <div class="comment-box">
                <ul>
                    <li v-for="(reply, index) in replies" :key="index" class="comment-item">
                        <div class="user">
                            <van-image class="avatar" :src="proxyImageUrl(reply.member?.avatar)"
                                radius="32"></van-image>
                            <div class="info">
                                <div class="username">{{ reply.member?.uname }}</div>
                                <div class="rating-time">
                                    <div class="rating">
                                        <template v-if="reply.rcount > 0">
                                            <van-icon name="star" v-for="(icount, index) in 5" :key="index" />
                                        </template>
                                    </div>
                                    <div class="time">{{ formatTime(reply.ctime) }}</div>
                                </div>
                            </div>
                        </div>
                        <div class="comment-content">{{ reply.content?.message }}</div>
                    </li>
                </ul>
            </div>
        </div>
        <div class="recommended ">
            <div class="title">猜你喜欢</div>
            <ul class="recommended-box">
                <li class="recommended-item" v-for="(recommend, index) in recommends" :key="index"
                    @click="goToDetail(recommend.season_id)">
                    <van-image class="cover" :src="proxyImageUrl(recommend.vertical_cover)" fit="cover"></van-image>
                    <div class="info">
                        <h2 class="title">{{ recommend.title }}</h2>
                        <p class="last_chapter">更新至{{ recommend.last_short_title }}话</p>
                    </div>
                </li>
            </ul>
        </div>
    </template>




</template>
<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { fetchComicDetail, fetchComicHotComments, fetchRecommended } from '@/api/index'
import { proxyImageUrl, formatTime } from "@/tool/index"
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()

import { useStore } from '@/pinia/index'

const store = useStore()

const props = defineProps({
    id: {
        type: String,
    }
});
import Logo from "@/assets/logo.png"
// ID 获取
const detail_id = computed(() => props.id || route.params.id)
const comic = reactive({
    id: '',
    title: '',
    horizontal_cover: '',
    author_name: [],
    styles: [],
    introduction: '',
    classic_lines: '',
    ep_list: [],
    ascending_ep_list: [],
    tags: [],
    total: 0
})

const isShow = ref(false)
const currentChapterId = ref()

// 章节菜单
const menus = ref([])
// 评论
const replies = ref([])
// 推荐
const recommends = ref([])
const loading = ref(true)
// 作者格式化
const getAuthors = (authors) => {
    // authors 是一个数组，里面包含多个作者,数组元素就是作者名称，需要把作者名称拼接成字符串，中间用”.“分割
    return authors.join("、")
}
// 获取最近免费章节
const getLastFreeEp = (ep_list) => {
    // console.log("ep_list:", ep_list)
    // 检查 ep_list 是否存在且为数组
    // if (!Array.isArray(ep_list) || ep_list.length === 0) {
    //     return 0;
    // }
    // 查找符合条件的章节（免费且未锁定）
    // const freeEp = ep_list.find(ep => ep.pay_mode === 0 && !ep.is_locked);
    // 检查是否找到了符合条件的章节
    // if (freeEp) {
    //     return freeEp.ord;
    // } else {
    //     // 如果没有找到免费章节，返回默认值 0
    //     return 0;
    // }
    const freeEp = ep_list.find(ep => ep.pay_mode === 0 && !ep.is_locked);
    if (freeEp) {
        return freeEp.ord;
    } else {
        // 如果没有找到免费章节，返回默认值 0
        return 0;
    }
}
//获取tag
const getTags = (tags) => {
    // tags 是一个数组，里面包含多个标签，格是为 {name: "标签名称", id: "id值"}
    // 需要提取对象内的name属性值，组合成新的数组
    let newTags = tags.map(item => item.name)
    newTags.unshift(comic.styles[0])
    return newTags
}
// 星星生成器
const getStars = (rcount) => {
}
const toggleStatus = ref(true) // 收起来状态
const toggleIcon = computed(() => {
    return toggleStatus.value ? 'arrow-down' : 'arrow-up'
})
const ascending = ref(true) //升序？降序？
const sortingOrder = computed(() => {
    return ascending.value ? '升序' : '降序'
})
const sortingOrderIcon = computed(() => {
    return ascending.value ? 'ascending' : 'descending'
})
// 调整漫画排序方式
const selectSort = () => {
    ascending.value = !ascending.value
    if (ascending.value) {
        // 升序
        menus.value = comic.ascending_ep_list
    } else {
        // 降序
        menus.value = comic.ep_list
    }
    store.setChapters_id(menus.value.map(menu => menu.id))
    // console.log('menus:', menus.value)
}
onMounted(async () => {
    loading.value = true
    await getComicDetail(detail_id.value)
    menus.value = comic.ascending_ep_list
    store.setChapters_id(menus.value.map(menu => menu.id))
    await getComicHotComments(detail_id.value)
    await getRecommended(detail_id.value)
    loading.value = false
});

watch(() => detail_id.value, async (newId, oldId) => {
    if (newId != oldId) {
        loading.value = true
        await getComicDetail(newId)
        menus.value = comic.ascending_ep_list
        await getComicHotComments(newId)
        await getRecommended(newId)
        loading.value = false
    }

})


const getComicDetail = async (id) => {
    const { data } = await fetchComicDetail(id)
    // console.log("详情:", data)
    comic.id = data.id
    comic.title = data.title
    comic.horizontal_cover = data.horizontal_cover
    comic.author_name = data.author_name
    comic.styles = data.styles
    comic.introduction = data.introduction
    comic.classic_lines = data.classic_lines
    comic.ep_list = data.ep_list //降序

    store.set_comic_sessions(data.ep_list.map(item => item.short_title))

    comic.ascending_ep_list = data.ep_list.slice().reverse(); // 升序
    comic.tags = data.tags
    comic.total = data.total
};
const getComicHotComments = async (id) => {
    const { data: { replies: repliesData } } = await fetchComicHotComments(id)
    replies.value = repliesData;
    // console.log("replies:", replies.value)
}
const getRecommended = async (id) => {
    const { data } = await fetchRecommended(id)
    // console.log("Recommended:", data)
    recommends.value = data;
};

const goToDetail = (id) => {
    router.push({ path: `/detail/${id}` })

};

const goToShow = (menu, lockedStatus) => {

    console.log("id:", menu.id)

    store.set_comic_id(detail_id.value)
    store.set_comic_short_title(menu.short_title)
    store.set_comic_title(comic.title)

    store.set_comic_chapter_isLocked(lockedStatus)

    router.push({ path: `/show/${menu.id}` })
};

const goBack = () => {
    router.go(-1)
}

</script>
<style scoped lang="scss">
.loading {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

.header {
    height: 44px;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
    background-color: #fff;
    position: relative;

    .back {
        position: absolute;
        left: 10px;
    }

    .title {}
}

.recommend {
    height: 50px;
    display: flex;
    align-items: center;

    .logo {
        height: 40px;
        overflow: hidden;
    }

    .slogan {
        p {
            margin: 0;
            color: #1c1d1f;
            font-size: 12px;
            font-weight: 400;
        }
    }

    .openApp {
        margin-left: auto;
        height: 44px;
        display: flex;
        /* 添加此行 */
        align-items: center;
        /* 添加此行 */
        padding-right: 10px;

        .button {
            height: 30px;
        }
    }
}

.banner {
    position: relative;

    .cover {
        position: relative;
    }

    .info {
        position: absolute;
        bottom: 5px;
        left: 10px;
        color: #fff;
        text-shadow: 0 .08333rem .25rem rgba(0, 0, 0, .5);
        font-weight: 500;

        .title {
            font-size: 20px;
            margin-bottom: 10px;
        }

        .other {
            font-size: 12px;
        }
    }
}

.subscribe {
    display: flex;
    align-items: center;
    justify-content: space-around;
    margin-top: 10px;

    .collection {
        display: flex;
        align-items: center;
    }

    .button {
        width: 200px;
        font-size: 16px;
    }
}

.tags {
    margin-top: 20px;
    padding: 0 10px;

    ul {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        justify-content: flex-start;
        gap: 10px;

        li {
            list-style: none;
            color: #6c6f7e;
            font-size: 12px;
            border: 1px solid rgba(0, 0, 0, 0.1);
            padding: 2px 6px;
            border-radius: 4px;
            height: 24px; // 固定高度
            line-height: 1;
            display: flex; // 使用flex布局
            align-items: center; // 垂直居中
            justify-content: center; // 水平居中
        }
    }
}

.classic_lines {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 20px;

    p {
        margin: 0;
        padding-left: 10px;
        font-size: 14px;
        color: #90929b;
        // padding: 10px 0 10px 10px;
        // 添加以下样式控制行数显示
        display: -webkit-box;
        -webkit-box-orient: vertical;
        overflow: hidden;
        // 默认显示一行
        -webkit-line-clamp: 1;

        // 根据toggleStatus切换显示行数
        &.expanded {
            -webkit-line-clamp: unset;
        }
    }

    .toggle {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        color: #6c727e;
        padding: 5px 10px 0px 10px;
        cursor: pointer;
        white-space: nowrap;
        margin-right: 10px;
        margin-top: auto;
    }
}

.chapter-menu {
    padding: 0 10px;
    border-top: 1px solid rgba(0, 0, 0, 0.1);
    margin-top: 20px;

    .title {
        color: #212121;
        font-size: 16px;
        font-weight: 500;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 20px 10px;

        .sorting {
            display: flex;
            align-items: center;
            font-size: 14px;
            color: #505050;
        }
    }

    .menu-box {
        padding: 0 10px;
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 10px;

        .menu-btn {
            position: relative;
            border: 1px solid #ccc;
            border-radius: 4px;
            color: #212121;
            font-size: 14px;
            padding: 5px;
            text-align: center;
            height: 40px;
            // 优化居中对齐
            display: flex;
            align-items: center;
            justify-content: center;
            // 处理文字换行
            word-break: break-all;
            overflow: visible;

            span {
                display: flex;
                align-items: center;
                justify-content: center;
                text-align: center;
            }

            .lock {
                position: absolute;
                top: -10px;
                right: 0;
                flex-shrink: 0;
                z-index: 10;
            }
        }
    }
}

.comments {
    margin-top: 20px;
    padding: 0 10px;

    .title {
        margin-bottom: 10px;
        font-size: 16px;
        padding-left: 10px;
    }

    .comment-box {
        padding: 0 10px;

        ul {
            display: flex;
            flex-wrap: nowrap;
            align-items: center;
            justify-content: flex-start;
            gap: 10px;
            overflow-x: auto;
            overflow-y: hidden;
            padding: 0;
            /* 移除默认内边距 */
            width: 100%;
            /* 确保容器宽度适当 */
            -webkit-overflow-scrolling: touch;
            margin-bottom: 20px;
            /* 隐藏滚动条但保持滚动功能 */
            scrollbar-width: none;
            /* Firefox */
            -ms-overflow-style: none;

            /* IE 10+ */
            &::-webkit-scrollbar {
                display: none;
                /* Chrome Safari */
            }

            /* 使移动端滚动更流畅 */
            .comment-item {
                flex: 0 0 auto;
                list-style: none;
                height: 120px;
                width: 250px;
                border: 1px solid rgba(0, 0, 0, 0.1);
                display: flex;
                flex-direction: column;
                box-sizing: border-box;
                padding: 10px;

                .user {
                    display: flex;
                    align-items: center;
                    justify-content: flex-start;
                    margin-bottom: 10px;

                    .avatar {
                        width: 32px;
                        height: 32px;
                        border-radius: 50%;
                    }

                    .info {
                        .username {}

                        .rating-time {
                            display: flex;
                            align-items: center;
                            justify-content: space-between;

                            .rating {}

                            .time {}
                        }
                    }
                }

                .comment-content {
                    overflow: hidden;
                    text-overflow: ellipsis;
                    display: -webkit-box;
                    -webkit-line-clamp: 3;
                    /* 限制显示3行 */
                    -webkit-box-orient: vertical;
                    word-wrap: break-word;
                    word-break: break-all;
                }
            }
        }
    }
}

.recommended {
    padding: 0 20px 20px 20px;

    .title {
        margin-bottom: 10px;
        font-size: 16px;
    }

    ul.recommended-box {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 10px;

        li.recommended-item {
            .cover {}

            .info {
                .title {
                    font-size: 14px;
                    font-weight: 400;
                    color: #222;
                    margin: 0 0 5px 0;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    display: -webkit-box;
                    -webkit-line-clamp: 1;
                    /* 限制显示3行 */
                    -webkit-box-orient: vertical;
                }

                .last_chapter {
                    font-size: 12px;
                    color: #999;
                    margin: 0
                }
            }
        }
    }
}

.fullscreen-popup {
    height: 100vh !important;
    /* 强制覆盖默认高度 */
    width: 100vw !important;
    /* 宽度铺满 */
}
</style>